package com.tvunetworks.center.user.util;

import com.tvunetworks.center.common.conf.properties.AccessProperties;
import com.tvunetworks.center.common.model.param.AccessParam;
import com.tvunetworks.center.common.util.EndecryptUtil;
import com.tvunetworks.center.common.util.JsonUtil;
import com.tvunetworks.center.common.util.MyUtil;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.user.service.feign.AccessFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @program:
 * @description:
 * @author HenryChen
 * @create: 9/27/2019 2:33 PM
 **/
@Component
@Slf4j
@EnableConfigurationProperties(AccessProperties.class)
public class AccessServerUtil {

    @Autowired
    private AccessProperties accessProperties;

    @Autowired
    private AccessFeignService accessFeignService;

      private String getAccessTimestamp() {
        Result timestamp = accessFeignService.getTime();
        return timestamp.getResult() + "";
    }

    /**
     *
     * @return String
     * @throws IOException 编译异常
     */
    public String generatorAccess() throws IOException {
        String requestId = MyUtil.getUUID();
        String appKey = accessProperties.getAppKey();
        String appSecret = accessProperties.getAppSecret();
        String timestamp = getAccessTimestamp();
        String signature = EndecryptUtil.MD5(appSecret + timestamp);

        return JsonUtil.toJsonStr(new AccessParam()
                .setAppkey(appKey)
                .setTimestamp(timestamp)
                .setSignature(signature)
                .setRequestId(requestId));
    }

//    public void handleServerAccessResult(Result result) {
//        String errorCode = result.getErrorCode();
//        // 810 开头说明是 timestampaccess 服务给的异常
//        if (!StringUtils.equals(errorCode, result.getErrorCode()) && StringUtils.startsWith(errorCode,"810")) {
//            throw new ServerAccessAuthException(result.getErrorInfo());
//        }
//    }


}
